import 'package:sqflite/sqflite.dart';

const kDataBaseName = "key_value_db.db";

const kSvaeSql = '';
void _createTable(Database db, int version) async {
  await db.execute('''CREATE TABLE IF NOT EXISTS  keyValue(
    `key` TEXT NOT NULL PRIMARY KEY,
    value TEXT NOT NULL
) ''');
}

class SqlBase {
  late Database db;

  open() async {
    db = await openDatabase(kDataBaseName, version: 1, onCreate: _createTable);
  }

  save({
    required String key,
    required String value,
  }) async {
    await db.rawInsert(
        'INSERT OR REPLACE INTO  keyValue(`key`, value) VALUES (?, ?)',
        [key, value]);
  }

  Future<String?> get({required String key}) async {
    final list =
        await db.rawQuery('SELECT * FROM keyValue WHERE `key` = ?', [key]);

    if (list.isNotEmpty) {
      return list[0]['value'] as String;
    }
    return "";
  }

  delete(String key) async {
    await save(key: key, value: "");
  }

  Future<Map<String, String>> getAll() async {
    final Map<String, String> map = Map();
    final list = await db.rawQuery(
      'SELECT * FROM keyValue',
    );

    for (final element in list) {
      String key = element['key'] as String;
      String value = element['value'] as String;
      map[key] = value;
    }

    return map;
  }
}
